<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Models\Post;
use App\Models\Comment;
use App\Models\PostReaded;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use League\Fractal\Pagination\Cursor;
use App\Transformers\CommentTransformer;

class CommentController extends BaseController
{
    /**
     * @api {get} /posts/{conId}/comments 评论列表(post comment list)
     * @apiDescription 评论列表(post comment list)
     * @apiGroup Post
     * @apiPermission none
     * @apiParam {String='user'} include  include
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 200 OK
     *   {
     *    "data": {
			"readNumer": 193,
			"commentList": [{
					"id": 1,
					"owner": false,
					"hasLike": false,
					"likeNum": 2,
					"avatarUrl": "https://inews.gtimg.com/newsapp_ls/0/13797755537/0",
					"nickName": "超长昵称超长...",
					"content": "啦啦啦啦",
					"parentId": null,
					"createTime": "2021-07-02 16:32:07"
				},
				{
					"id": 2,
					"owner": false,
					"hasLike": false,
					"likeNum": 2,
					"avatarUrl": "https://inews.gtimg.com/newsapp_ls/0/13797761970/0",
					"nickName": "寂寞无敌",
					"content": "我是评论的评论",
					"parentId": 1,
					"createTime": "2021-07-02 17:05:50"
				},
				{
					"id": 4,
					"owner": true,
					"hasLike": true,
					"likeNum": 1,
					"avatarUrl": "https://inews.gtimg.com/newsapp_ls/0/13797763270/0",
					"nickName": "name111",
					"content": "评论啦啦啦啦啦啦啦啦啦啦",
					"parentId": null,
					"createTime": "2021-07-13 09:37:50"
				},
				{
					"id": 5,
					"owner": false,
					"hasLike": false,
					"likeNum": 0,
					"avatarUrl": "https://inews.gtimg.com/newsapp_ls/0/13797755537/0",
					"nickName": "超长昵称超长...",
					"content": "超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论超长评论",
					"parentId": null,
					"createTime": "2021-07-13 16:04:35"
				},
				{
					"id": 13,
					"owner": false,
					"hasLike": false,
					"likeNum": 0,
					"avatarUrl": "https://inews.gtimg.com/newsapp_ls/0/13797755537/0",
					"nickName": "超长昵称超长...",
					"content": "@寂寞无敌 你怕不是个大聪明",
					"parentId": 1,
					"createTime": "2021-07-14 11:01:23"
				}
			],
     *    "meta": {
     *      "pagination": {
     *        "total": 3,
     *        "count": 3,
     *        "per_page": 15,
     *        "current_page": 1,
     *        "total_pages": 1,
     *        "links": []
     *      }
     *    }
	 *   },
     *  }
     */
    public function index($conId, Request $request)
    {
		$conType = $request->get('conType');
		\Log::info('comments index request conId: '.$conId.' conType: '.$conType);
		$retData = [
			"readNumer" => 0,
			"commentList" => []
		];
		$post = Post::where('con_id', $conId)->where('con_type', $conType)->first();
		if(!$post){
			return $this->returnSuccess($retData);
		}
		\Log::info('comments post : '.var_export($post->id, true));
		$postRead = PostReaded::where('post_id', $post->id)->first();
		if($postRead){
			$retData['readNumer'] = $postRead->read_num;
		}
		$comments = Comment ::where('post_id', $post->id)->get();
		// \Log::info('comments comments : '.var_export($comments, true));
		//累加次数
		$incRet = DB::insert("insert into posts_read(post_id) values(".$post->id.") on DUPLICATE KEY UPDATE read_num=read_num+1");
        
		$dataArry = $comments->toArray();
		
		$userIds = field_vals($dataArry, 'user_id');
		$userIds = array_unique($userIds);
		$users = User::whereIn('id', $userIds)->get();
		$userKv = kv_rows($users, 'id');
		$commentList = [];
		$user = $this->user();
		$userId = $user ? $user->id : 0;
		foreach($comments as $comment){
			$likeArr = json_decode($comment->like, true);
			$likeNum = count($likeArr);
			
			if(!isset($userKv[$comment->user_id])){
				continue;
			}
			$avatarUrl = env('CUT_APP_STATIC') . $userKv[$comment->user_id]['headimg'];
			$commentList[] = [
				'id' => $comment->id,
				'owner' => ($userId == $comment->user_id or $userId == env('ADMIN_USER_ID')) ? true : false,
				'hasLike' => in_array($userId, $likeArr),
				'likeNum' => $likeNum,
				'avatarUrl' => $avatarUrl,
				'nickName' => "". $userKv[$comment->user_id]['name'],
				'content' => $comment->content,
				'parentId' => $comment->parent_id,
				'createTime' => date('Y-m-d H:i:s', strtotime($comment->created_at)),
			];
		}
		$retData['commentList'] = $commentList;
		
        return $this->returnSuccess($retData);
    }

    /**
     * @api {post} /posts/{conId}/comments 发布评论(create post comment)
     * @apiDescription 发布评论(create post comment)
     * @apiGroup Post
     * @apiPermission jwt
     * @apiParam {String} content  post content
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 201 Created
     */
    public function store($conId, Request $request)
    {
		$conType = $request->get('conType');
		$parentId = $request->get('parent_id');
		
        $validator = \Validator::make($request->all(), [
            'content' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->returnFail('发表内容不合规');
        }
		$post = Post::where('con_id', $conId)->where('con_type', $conType)->first();
		if(!$post){
			return $this->returnFail('发表内容不合规');
		}

        $user = $this->user();

        $comment = new Comment;
        $comment->content = $request->get('content');
        $comment->user_id = $user->id;
        $comment->post_id = $post->id;
        $comment->parent_id = $parentId;
        $comment->status = 1;
        $comment->like = '[]';
        $comment->save();

        return $this->returnSuccess('');
    }

	/**
     * @api {post} /posts/{commentId}/comments/like 发布评论(like post comment)
     * @apiDescription 点赞评论(like post comment)
     * @apiGroup Post
     * @apiPermission jwt
     * @apiParam {String} content  post content
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 201 Created
     */
    public function like($commentId, Request $request)
    {

        $comment = Comment::findOrFail($commentId);
		if(!$comment->id){
			return $this->returnFail('不存在评论ID');
		}
		$user = $this->user();
		$oldJson = $comment->like;
		$oldLikeArr = json_decode($oldJson, true);
        if(in_array($user->id, $oldLikeArr)){
			$likeArr = array_diff($oldLikeArr, [$user->id]);
		}else{
			$oldLikeArr[] = $user->id;
			$likeArr = $oldLikeArr;
		}
		$likeJson = json_encode($likeArr);
		$attributes = [
			'like' => $likeJson,
		];
        $data = $comment->update($attributes);

		return $this->returnSuccess($data);
        // return $this->response->item($comment, new CommentTransformer())
        //     ->setStatusCode(201);
    }

    /**
     * @api {delete} /posts/{conId}/{conType}/comments/{id} 删除评论(delete post comment)
     * @apiDescription 删除评论(delete post comment)
     * @apiGroup Post
     * @apiPermission jwt
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 204 NO CONTENT
     */
    public function destroy($conId, $conType, $id)
    {
		$post = Post::where('con_id', $conId)->where('con_type', $conType)->first();
		if(!$post){
			return $this->returnFail('发表内容不合规');
		}
		\Log::info("conId $conId id $id conType $conType post_id ".$post->id);
        $comment = Comment::where('post_id', $post->id)
            ->where('id', $id)
            ->firstOrFail();

        if ($comment->user_id != $this->user()->id) {
            abort(403);
        }

        $ret = $comment->delete();

        return $this->returnSuccess($ret);
    }
}
